//
//  QaController.swift
//  flowerpot
//
//  Created by fyname on 15/10/14.
//  Copyright © 2015年 senhe. All rights reserved.
//

import UIKit

class QaController: UITableViewController,UMSocialUIDelegate {

    @IBAction func ShareQa(sender: AnyObject) {
        
        
        //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
        UMSocialSnsService.presentSnsController(self, appKey: Common.UMkey, shareText: "@友盟分享测试啦!", shareImage: UIImage(named:("xingxing_yellow"))!, shareToSnsNames: [UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ], delegate: self)
        
        //UMSocialSnsService.presentSnsIconSheetView(self, appKey:"56557a2467e58e59910005fb", shareText:"很好玩的小游戏,小时都玩过吧!https://github.com/c-shen", shareImage: UIImage(named:"xingxing_yellow"), shareToSnsNames: [UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToTencent,UMShareToRenren,UMShareToDouban, UMShareToFacebook,UMShareToLine, UMShareToQzone,UMShareToQQ], delegate: self)
    }
    
    
    // default datas
    var datas:Int = 0
    
    var listVideos : NSMutableArray!

    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        let bundle = NSBundle.mainBundle()
        let plistPath : String! = bundle.pathForResource("videos", ofType: "plist")
        listVideos = NSMutableArray(contentsOfFile: plistPath)
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        //下面这段话是设置左边编辑，右边添加item
        
        //self.navigationItem.leftBarButtonItem = self.editButtonItem()
        //let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "insertNewObject:")
        //self.navigationItem.rightBarButtonItem = addButton
        
        
        weak var weakSelf = self as QaController
        
        // 上拉动画
        self.tableView.headerViewRefreshAnimationStatus(.headerViewRefreshArrowAnimation, images: [])
        
        self.tableView.hiddenFooterView()
        // 上啦加载更多
        self.tableView.toLoadMoreAction({ () -> () in
            print("toLoadMoreAction success")
            if (weakSelf?.datas < 10){
                weakSelf?.datas += 10
                weakSelf?.tableView.reloadData()
                weakSelf?.tableView.doneRefresh()
            }else{
                weakSelf?.tableView.endLoadMoreData()
            }
        })
        
        // 及时上拉刷新
        self.tableView.nowRefresh({ () -> Void in
            weakSelf?.delay(2.0, closure: { () -> () in})
            weakSelf?.delay(2.0, closure: { () -> () in
                print("nowRefresh success")
                weakSelf?.datas += 10
                self.tableView.showFooterView()
                weakSelf?.tableView.reloadData()
                weakSelf?.tableView.doneRefresh()
            })
        })
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
       return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return listVideos.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let qaCell:String = "qaCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(qaCell, forIndexPath: indexPath) as! QaCell

        // Configure the cell...
        let row = indexPath.row
        let rowDict : NSDictionary = listVideos.objectAtIndex(row) as! NSDictionary
        let url : String = rowDict.objectForKey("video_img") as! String
        let dataImg : NSData = NSData(contentsOfURL: NSURL(string : url)!)!
        cell.qaImage.image = UIImage(data: dataImg)
        cell.qaTitle.text = rowDict.objectForKey("video_title") as? String
        cell.qaTime.text = "2015-10-10 12:22"
        
        return cell
    }
    

    
    //给新进入的界面进行传值
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if segue.identifier == "qaShowDetail" {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                let object : NSDictionary = listVideos[indexPath.row] as! NSDictionary
                (segue.destinationViewController as! QaDetailController).detailItem = object
                log.debug("qac to detail: \(object)")
            }
        }
    }

    
    
    
    func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
    
    func didFinishGetUMSocialDataInViewController(response:UMSocialResponseEntity){
        //根据`responseCode`得到发送结果,如果分享成功
        if(response.responseCode == UMSResponseCodeSuccess)
        {
            //得到分享到的微博平台名
            log.debug("分享成功!")
        }else{
            log.debug("分享失败!")
        }
    }
}
